package table;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class ResultSetTableModel extends AbstractTableModel {
	private   ResultSet rs;
    private   ResultSetMetaData rsmd;
    protected ArrayList cache;
	
    //http://pt.wikinourau.org/bin/view/GrupoJava/ArtigoSwingComBD
    
	 public ResultSetTableModel(ResultSet aResultSet){
         rs = aResultSet;
         try {
                 rsmd = rs.getMetaData();
                 cache = new ArrayList();
                 //os dados da consulta  são armazenados no cache.
                 while (rs.next()) {
                         Object[] row = new Object[rsmd.getColumnCount()];
                         for (int j=0;j<row.length;j++)
                         row[j] = rs.getObject(j+1);
                         cache.add(row);
                 }
                 
         } catch(SQLException e) {
                 System.out.println("Error " + e);
         }      
 }//fim bloco construtor

	public int getRowCount() {
		// TODO Auto-generated method stub
		return cache.size();
	}

	 public String getColumnName(int c) {
	      try {
	         return rsmd.getColumnName(c + 1);
	      } catch(SQLException e){
	         System.out.println("Error " + e);
	         return "";
	      }
	   }
	 public int getColumnCount(){
	      try{
	         return rsmd.getColumnCount();
	      } catch(SQLException e) {
	         System.out.println("Error " + e);
	         return 0;
	      }
	   }

	 public Object getValueAt(int r,int c){
	       if(r < cache.size())
	          return ((Object[]) cache.get(r))[c];
	       else
	          return null;
	 }

}
